import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';

import 'index.dart';

class MessageIndexPage extends GetView<MessageIndexController> {
  const MessageIndexPage({super.key});

  // 主视图
  Widget _buildView() {
    return Column(
      children: [
        // 聊天列表
        Expanded(
          child: GetBuilder<MessageIndexController>(
            init: MessageIndexController(),
            builder: (controller) => RefreshIndicator(
              onRefresh: controller.pullToRefresh,
              color: const Color(0xFFE33641),
              backgroundColor: Colors.white,
              strokeWidth: 2.5,
              displacement: 40.0,
              child: Obx(() {
                // 🔄 显示加载状态
                if (controller.isLoadingFriends.value && controller.chatList.isEmpty) {
                  return ListView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    children: const [
                      SizedBox(height: 200),
                      Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            CircularProgressIndicator(
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                            SizedBox(height: 16),
                            Text(
                              '正在加载好友列表...',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  );
                }
                
                // 📭 空状态（支持下拉刷新）
                if (controller.chatList.isEmpty) {
                  return ListView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    children: const [
                      SizedBox(height: 200), // 给下拉留出空间
                      Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.chat_bubble_outline,
                              size: 64,
                              color: Colors.white,
                            ),
                            SizedBox(height: 16),
                            Text(
                              '暂无好友',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 18,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            SizedBox(height: 8),
                            Text(
                              '点击右上角添加好友开始聊天',
                              style: TextStyle(
                                color: Colors.white70,
                                fontSize: 14,
                              ),
                            ),
                            SizedBox(height: 16),
                            Text(
                              '下拉可刷新好友列表',
                              style: TextStyle(
                                color: Colors.white60,
                                fontSize: 12,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 200), // 底部留白，确保能够下拉
                    ],
                  );
                }
                
                // 📝 好友列表
                return ListView.builder(
                  physics: const AlwaysScrollableScrollPhysics(),
                  itemCount: controller.chatList.length,
                  itemBuilder: (context, index) {
                    final chat = controller.chatList[index];
                    return Container(
                      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                      child: Dismissible(
                        key: Key('chat_${chat.id}'),
                        direction: DismissDirection.endToStart,
                        background: Container(
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(16),
                          ),
                          alignment: Alignment.centerRight,
                          padding: const EdgeInsets.only(right: 20),
                          child: const Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.delete_outline,
                                color: Colors.white,
                                size: 28,
                              ),
                              SizedBox(height: 4),
                              Text(
                                '删除',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ],
                          ),
                        ),
                        confirmDismiss: (direction) async {
                          return await controller.showDeleteConfirmDialog(chat);
                        },
                        onDismissed: (direction) {
                          controller.deleteFriend(chat.id, chat.name);
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(16),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.1),
                                blurRadius: 4,
                                offset: const Offset(0, 2),
                              ),
                            ],
                          ),
                          child: ListTile(
                            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                            leading: GestureDetector(
                              onTap: () => controller.goToUserProfile(chat), // 🎯 点击头像跳转到用户信息页面
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(25),
                                child: CachedNetworkImage(
                                  imageUrl: chat.avatarUrl,
                                  width: 50,
                                  height: 50,
                                  fit: BoxFit.cover,
                                  // 图片加载失败时显示占位图
                                  errorWidget: (context, url, error) {
                                    return Container(
                                      width: 50,
                                      height: 50,
                                      color: Colors.grey[300],
                                      child: const Icon(Icons.person, color: Colors.grey),
                                    );
                                  },
                                ),
                              ),
                            ),
                            title: Text(
                              chat.name,
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 16,
                              ),
                            ),
                            subtitle: Text(
                              chat.lastMessage,
                              style: TextStyle(
                                color: Colors.grey[600],
                                fontSize: 14,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            trailing: chat.isUnread
                                ? Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                    decoration: BoxDecoration(
                                      color: const Color(0xFFE33641),
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    child: const Text(
                                      '新消息',
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 11,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  )
                                : null,
                            onTap: () => controller.goToChatDetail(chat),
                          ),
                        ),
                      ),
                    );
                  },
                );
              }),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    // 设置状态栏为透明，图标为亮色
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));

    return GetBuilder<MessageIndexController>(
      init: MessageIndexController(),
      id: "message_index",
      global: false, // 确保控制器不被全局共享，避免冲突
      autoRemove: false, // 防止控制器被自动销毁
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFE33641), // 红色背景色
          appBar: AppBar(
            backgroundColor: const Color(0xFFE33641),
            elevation: 0,
            centerTitle: true,
            title: const Text(
              "我的聊天",
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
           leading: IconButton(
              icon: const Icon(
                Icons.arrow_back_ios,
                color: Colors.white,
                size: 20,
              ),
              onPressed: () => Get.back(),
            ),
            actions: [
              // 🔥 添加好友图标（带小黄点通知）
              GestureDetector(
                onTap: () => controller.addNewContact(),
                child: Stack(
                  children: [
                    // 添加好友图标
                    Container(
                      padding: const EdgeInsets.all(12),
                      child: const Icon(
                        Icons.person_add_outlined, 
                        color: Colors.white,
                        size: 24,
                      ),
                    ),
                    // 🔥 小黄点通知（当有好友申请时显示）
                    Obx(() => controller.hasFriendRequestNotification.value
                        ? Positioned(
                            right: 8,
                            top: 8,
                            child: Container(
                              width: 10,  // 🔥 修复：统一尺寸为10px，符合MyApplication2标准
                              height: 10, // 🔥 修复：统一尺寸为10px，符合MyApplication2标准
                              decoration: const BoxDecoration(
                                color: Color(0xFFFFD700), // 黄色小点
                                shape: BoxShape.circle,
                              ),
                            ),
                          )
                        : const SizedBox.shrink()),
                  ],
                ),
              ),
            ],
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}
